package org.redr.canvas;

import java.io.File;
import java.util.ArrayList;

import org.redr.widgetGUI.core.Button;
import org.redr.widgetGUI.core.TextEdit;
import org.redr.widgetGUI.core.WidgetBox;
import org.redr.widgetGUI.settings.RedRSettings;
import org.redr.widgetGUI.settings.WidgetSettings;

import com.trolltech.qt.core.QCoreApplication;
import com.trolltech.qt.core.QEvent;
import com.trolltech.qt.core.Qt;
import com.trolltech.qt.gui.QApplication;
import com.trolltech.qt.gui.QCloseEvent;
import com.trolltech.qt.gui.QDockWidget;
import com.trolltech.qt.gui.QIcon;
import com.trolltech.qt.gui.QMainWindow;
import com.trolltech.qt.gui.QMessageBox;
import com.trolltech.qt.gui.QPushButton;
import com.trolltech.qt.gui.QSizePolicy;
import com.trolltech.qt.gui.QStatusBar;
import com.trolltech.qt.gui.QTabWidget;
import com.trolltech.qt.gui.QTextCursor;
import com.trolltech.qt.gui.QToolBar;


public class RedRCanvas extends QMainWindow{
    
	WidgetBox controlArea;
	TextEdit notes;
	TextEdit printOutput;
	QDockWidget notesDock;
	QDockWidget outputDock;
	RedRSettings settings;
	Button showNotesButton;
    Button showWidgetToolbar;
    Button showROutputButton;
	QDockWidget  widgetDock;
	ArrayList<String> tabsList = new ArrayList<String>();
	QTabWidget tabs;
	
	private String _(String s)
	{
		return s;
	}
	
	public RedRCanvas() //, parent = null, flags =  0)
	{
		settings = RedRApplication.settings;
        RedRLog.log("starting canvas dlg");
        
        setWindowTitle(_("Red-R Canvas ") + RedRApplication.coreSettings().getSetting("REDRVERSION"));
        File canvasIcon = OSPath.join(RedRApplication.parentDir, "coreIcons", "CanvasIcon.png");
        if (canvasIcon.isFile())
        {
            setWindowIcon(new QIcon(canvasIcon.toString()));
        }
               
        /*
         * Create the basis for the main window layout
         */
        
        //setLayout(new QVBoxLayout());
        controlArea = new WidgetBox(this.layout(), 
        		settings.getSettings("controlArea"));
        this.setCentralWidget(controlArea.widget());
        
        tabs = new QTabWidget();
        tabs.setDocumentMode(true);
        tabs.setTabsClosable(true);
        tabs.setMovable(true);
        tabs.setTabShape(QTabWidget.TabShape.Rounded);
        QPushButton plusButton = new QPushButton();
        plusButton.setIcon(new QIcon(OSPath.join(RedRApplication.parentDir, "coreIcons", "plus.png").toString()));
        plusButton.clicked.connect(this, "newTab()");
        
        tabs.setCornerWidget(plusButton);
        
        tabs.currentChanged.connect(this, "resetActiveTab(Integer)");
        
        controlArea.addWidget(tabs);
        
        addTab("General");
        
        RedRLog.log("Adding notes widget");
        /*
        ###############################
        #####Notes and output Docks####
        ###############################
        */
        
        notesDock = new QDockWidget(_("Notes"));
        notesDock.setObjectName(_("CanvasNotes"));
        // notesDock.setLayout(new QVBoxLayout());
        notesDock.layout().setWidgetSpacing(0);
        WidgetBox notesControl = new WidgetBox(settings.getSettings("notesControl"));
        WidgetSettings notesSettings = settings.getSettings("notes");
        notesSettings.setSetting("label", _("Notes"));
        notes = new TextEdit(notesControl, notesSettings);
        notes.widget().setMinimumWidth(200);
        notes.widget().show();
        notesDock.setWidget(notesControl.widget());
        addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, notesDock);
        notesDock.topLevelChanged.connect(this, "visibilityChanged(boolean)");
        
        RedRLog.log("connected notes dock");
        
        outputDock = new QDockWidget(_("Output"));
        outputDock.setObjectName(_("CanvasOutput"));
        // outputDock.setLayout(new QVBoxLayout());
        outputDock.layout().setWidgetSpacing(0);
        WidgetBox outputControl = new WidgetBox(outputDock.layout(), settings.getSettings("outputControl"));
        WidgetSettings outputSettings = settings.getSettings("output");
        outputSettings.setSetting("label", _("Output"));
        printOutput = new TextEdit(outputControl, outputSettings);
        
        WidgetBox outputBottomArea = new WidgetBox(outputControl, (WidgetSettings) settings.getSettings("outputBottomArea").setSetting("alignment", "left").setSetting("layout", "horizontal"));
        
        Button saveOutputButton = new Button(outputBottomArea, (WidgetSettings) settings.getSettings("saveOutput")
        		.setSetting("label", _("Save Output")));
        saveOutputButton.widget().setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Maximum);
        Button clearOutputButton = new Button(outputBottomArea, (WidgetSettings) settings.getSettings("clearOutput")
        		.setSetting("label", _("Clear Output")));
        clearOutputButton.widget().setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Maximum);
        Button browserButton = new Button(outputBottomArea, (WidgetSettings) settings.getSettings("browser")
        		.setSetting("label", _("Show In Browser")));
        browserButton.widget().setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Maximum);
        
        saveOutputButton.widget().clicked.connect(this, "saveOutputToFile()");
        clearOutputButton.widget().clicked.connect(this, "clearPrintOutput()");
        browserButton.widget().clicked.connect(this, "showLogFile()");
        
        
        
        //		redRbutton(hbox, label = _("Show in Browser"), callback = lambda: redRLog.fileLogger.showLogFile());	
		    
        
        outputDock.setWidget(outputControl.widget());
        RedRLog.connectTextEdit(printOutput);
        addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, outputDock);
        outputDock.topLevelChanged.connect(this, "visibilityChanged(boolean)");
        //#redRLog.setOutputWindow(self.printOutput)
        //redRLog.setOutputManager("dock", dockOutputManger);
        /*
        #######################
        #####Output Manager####
        #######################

        # self.output = redROutput.OutputWindow(self)
        # redRLog.setOutputManager("window", self.output.outputManager)
        
        
        /*
        ###################
        #Main Cavas########
        ###################
        */
        
        
        
        RedRApplication.splashWindowShowMessage(_("Main Cavas"), Qt.AlignmentFlag.AlignHCenter.value() + Qt.AlignmentFlag.AlignBottom.value());

        // TODO: Implement the schema
        //Schema schema = orngDoc.SchemaDoc(this);
        //setCentralWidget(schema);
        //schema.setFocus();
        
        /*
        ###################
        #Toolbar and Menu##
        ###################
        */
        
        RedRApplication.splashWindowShowMessage(_("Creating Menu and Toolbar"), Qt.AlignmentFlag.AlignHCenter.value() | Qt.AlignmentFlag.AlignBottom.value());
        QToolBar toolbar = addToolBar(_("Toolbar"));
        RedRToolbarAndMenu toolbarFunctions = new RedRToolbarAndMenu(this, toolbar);
        toolbarFunctions.updateStyle();
        
        /*
        ######################
        #Create Widgets Dock##
        ######################
        */
        
        widgetDock = new QDockWidget(_("Widgets"));
        widgetDock.setObjectName("widgetDock");
        // widgetDock.setLayout(new QVBoxLayout());
        WidgetBox widgetDockBox = new WidgetBox(settings.getSettings("widgetDockBox"));
        widgetDockBox.widget().setMinimumWidth(200);
        
        widgetDock.setWidget(widgetDockBox.widget());
        addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, widgetDock);
        widgetDock.topLevelChanged.connect(this, "visibilityChanged(boolean)");
        
        
        // WidgetTree widgetsToolBar = redRWidgetsTree.WidgetTree(widgetDockBox, this, widgetRegistry);
        // WidgetSuggest suggestButtonsList = redRWidgetsTree.widgetSuggestions(widgetDockBox, this);
        
        /*
        # self.createWidgetsToolbar() # also creates the categories popup
        # self.toolbar.addWidget(self.widgetsToolBar.widgetSuggestEdit) ## kind of a hack but there you are.        

        ###################
        #####Status Bar####
        ###################
        */
        
        RedRApplication.splashWindowShowMessage(_("Creating Status Bar"), Qt.AlignmentFlag.AlignHCenter.value() + Qt.AlignmentFlag.AlignBottom.value());
        
        QStatusBar statusBar = new QStatusBar();
        statusBar.setSizeGripEnabled(false);
        setStatusBar(statusBar);
        
        WidgetBox docBox = new WidgetBox((WidgetSettings) settings.getSettings("statusBarButtonsBox").setSetting("layout", "horizontal"));
        showWidgetToolbar = new Button(docBox, (WidgetSettings) settings.getSettings("showWidgetToolbarButton")
        		.setSetting("label", "")
        		.setSetting("toggleButton", "true")
        		.setSetting("toolTip", _("Widget Tree"))
        		.setDefault("on", "true"));
        showWidgetToolbar.widget().setIcon(new QIcon(OSPath.join(RedRApplication.parentDir, "coreIcons", "folders.png").toString()));
        
        //"", toggleButton=true, RedRStyle.defaultWidgetIcon, _("Widget Tree"), self.updateDockState);   
        
        showROutputButton = new Button(docBox, (WidgetSettings) settings.getSettings("showROutputButton")
        		.setSetting("label", "")
        		.setSetting("toggleButton", "true")
        		.setSetting("toolTip", _("Log"))
        		.setDefault("on", "false"));
        showROutputButton.widget().setIcon(new QIcon(OSPath.join(RedRApplication.parentDir, "coreIcons", "doc.png").toString()));
        		
        		//docBox, "", true, RedRStyle.canvasIcon, _("Log"), updateDockState); 

        showNotesButton = new Button(docBox, (WidgetSettings) settings.getSettings("showNotesButton")
        		.setSetting("label", "")
        		.setSetting("toggleButton", "true")
        		.setSetting("toolTip", _("Notes"))
        		.setDefault("on", "true"));
        showNotesButton.widget().setIcon(new QIcon(OSPath.join(RedRApplication.parentDir, "coreIcons", "help.png").toString()));
        		//docBox, "", true, RedRStyle.notesIcon, _("Notes"), updateDockState);
        
        
        statusBar.addPermanentWidget(docBox.widget());
        

        RedRApplication.splashWindowShowMessage(_("Creating Reports"), Qt.AlignmentFlag.AlignHCenter.value() + Qt.AlignmentFlag.AlignBottom.value());
        
        //self.reports = redRReports.reports(self,self.schema)


        RedRApplication.splashWindowShowMessage(_("Setting States"), Qt.AlignmentFlag.AlignHCenter.value() + Qt.AlignmentFlag.AlignBottom.value());

        //restoreState();
        //restoreGeometry();
        //resize();
        
        /*
        if "windowState" in RedREnviron.settings.keys():
            print self.restoreState(RedREnviron.settings["windowState"])


        if "geometry" in RedREnviron.settings.keys():
            self.restoreGeometry(RedREnviron.settings["geometry"])

        if "size" in RedREnviron.settings.keys():
            resize(RedREnviron.settings["size"])
        else:
        	width, height = RedREnviron.settings.get("canvasWidth", 700), RedREnviron.settings.get("canvasHeight", 600)
            desktop = app.desktop()
            deskH = desktop.screenGeometry(desktop.primaryScreen()).height()
            deskW = desktop.screenGeometry(desktop.primaryScreen()).width()
            h = max(0, deskH/2 - height/2)  # if the window is too small, resize the window to desktop size
            w = max(0, deskW/2 - width/2)
            self.move(w,h+2)
            self.resize(width,height)
        if "pos" in RedREnviron.settings.keys():
            self.move(RedREnviron.settings["pos"])

        */
        
        show();
        //redRSaveLoad.setCanvasDlg(this);
        //redRObjects.setCanvasDlg(this);
        
        try
        {
        	if (Boolean.parseBoolean(RedRApplication.coreSettings().getSetting("firstLoad")))
        		//redRInitWizard.startSetupWizard();
        		System.out.println("Thanks for loading Red-R");
        }
        catch (Exception e)
        {
            RedRLog.log(RedRLog.REDRCORE, RedRLog.ERROR, RedRLog.formatException(e));
            
        }
        
        // self.packageManager = redRPackageManager.packageManager(self)
        
        // if (Boolean.parseBoolean(app.coreSettings().getSetting("checkForPackageUpdates")) packageManager.exec_();
        //print "Processing events"
        QCoreApplication.processEvents();
        //print "events processed"
        //#redRInitWizard.startSetupWizard()
	}
	
    private void addTab(String string) {
		// TODO Auto-generated method stub
    	SchemaView generalView = new SchemaView(string);
    	generalView.show();
    	generalView.setToolTip("Tab to interact with widgets");
    
    	RedRObjects.addTab(string, generalView);
    	RedRObjects.setTab(string);
        tabsList.add(string);
        tabs.addTab(generalView, string);
	}

	public void saveOutputToFile()
    {
        // toolbarFunctions.menuItemSaveOutputWindow();
    }
    
    public void resetActiveTab(Integer i){
    	RedRObjects.setTab(tabs.tabText(i));
    }
    
    public void newTab(){
    	// TODO
    }
    
    public void dockOutputManger(String string, boolean html)
    {
    	QTextCursor cursor = new QTextCursor(printOutput.widget().textCursor());                
        cursor.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.MoveAnchor);      
        printOutput.widget().setTextCursor(cursor);                             
        if (html) printOutput.insertHtml(string);
        else printOutput.widget().insertPlainText(string);
        
        printOutput.widget().ensureCursorVisible();
        // printOutput.widget().verticalScrollBar().setValue(sb.maximum());
    }

    public void updateDock(QEvent ev)
    {
        if (notesDock.isHidden()) showNotesButton.setChecked(false);
        else showNotesButton.setChecked(true);
        
        if (outputDock.isHidden()) showROutputButton.setChecked(false);
        else showROutputButton.setChecked(true);
            
        if (widgetDock.isHidden()) showWidgetToolbar.setChecked(false);
        else showWidgetToolbar.setChecked(true);
    }       
    
    public void updateDockState()
    {
        //#print _("in updatedock right")
    	/*
        if ("dockState" not in RedREnviron.settings.keys())
        {
            RedREnviron.settings["dockState"] = {"notesBox":true, "outputBox":true, "widgetBox":true};
        }
        
        if (showNotesButton.isChecked())
        {
        	notesDock.show();
            RedREnviron.settings["dockState"]["notesBox"] = true;
        } 
        else 
        {
        	notesDock.hide();
        	RedREnviron.settings["dockState"]["notesBox"] = false;
       	}
        
        if (self.showROutputButton.isChecked())
        {
            outputDock.show();
            RedREnviron.settings["dockState"]["outputBox"] = true;
        }
        else
        {
            outputDock.hide();
            RedREnviron.settings["dockState"]["outputBox"] = false;
        }
        
        if (showWidgetToolbar.isChecked())
        {
            widgetDock.show();
            RedREnviron.settings["dockState"]["widgetBox"] = true;
        }
        else
        {
            widgetDock.hide();
            RedREnviron.settings["dockState"]["widgetBox"] = false;
        }
        */
    }
    
    public void createWidgetsToolbar(WidgetRegistry widgetRegistry)
    {
    	/*
        if (widgetRegistry != null)
        {
            thiswidgetRegistry = widgetRegistry;
        }
        widgetsToolBar.clear();
        widgetsToolBar.createWidgetTabs(widgetRegistry);
        */ 
    }
       
    public void setCaption(String caption)
    {
        caption = caption.split(".")[0];
        setWindowTitle(_("%s - Red Canvas") + caption);
    }
    
    public void setCaption()
    {
    	setCaption(_("RedR Canvas"));
    }
    
    @Override
	public void closeEvent(QCloseEvent ce)
    {
    	int res;
    	boolean closed;
        try
        {
            //#ce.accept()
        	/*
        	settings.setCoreSetting("geometry", saveGeometry().toString());
        	settings.setCoreSetting("windowState", saveState().toString());
        	settings.setCoreSetting("pos", pos().toString());
        	settings.setCoreSetting("size", size().toString());

            settings.saveCoreSettings();
            */
            int really = QMessageBox.question(this, _("Red-R Canvas"), _("Are you sure you want to shutdown?"), QMessageBox.StandardButton.Yes, QMessageBox.StandardButton.No);
            
            if (really != QMessageBox.StandardButton.Yes.value()){
            	ce.ignore();
            	return;
            }
            
            if (Boolean.parseBoolean(RedRApplication.coreSettings().getSetting("dontAskBeforeClose"))) res = QMessageBox.StandardButton.No.value();
            else res = QMessageBox.question(this, _("Red-R Canvas"), _("Do you wish to save the schema?"), QMessageBox.StandardButton.Yes, QMessageBox.StandardButton.No);
            
            if (res == QMessageBox.StandardButton.Yes.value())
            {
                GlobalData.setRVariableRemoveSupress(true);
                closed = RedRApplication.saveDocument();
            }
            else if (res == QMessageBox.StandardButton.No.value())
            {
                closed=true;
            }
            else
            {
                closed=false;
            }
            if (closed)
            {
                //if (postCloseFun)
                //{
                    //print "asdfasdfasfd"
                    //r = postCloseFun()
                    //print "a", r
                //}
                GlobalData.setCanvasIsClosing(true); //       # output window (and possibly report window also) will check this variable before it will close the window
                RedRObjects.closeAllWidgets(); // # close all the widget first so their global data is saved
                //import shutil
                //shutil.rmtree(RedREnviron.directoryNames["tempDir"], true) # remove the tempdir, better hope we saved everything we wanted.
                //# close the entire session dropping anything that was open in case it was left by something else, 
                //# makes the closing much cleaner than just loosing the session.
                
                // RedRHistory.saveConnectionHistory();
                // RedRLog.fileLogger.closeLogFile();
                //#redRLog.closeLogger()
                RSession.shutDown();
                System.out.println("Closing RedR");
                ce.accept();
                //super.closeEvent((QCloseEvent) ce);
                
            }
            else
            {
                ce.ignore();
            }
        }
        catch (Exception e)
        {
        	e.printStackTrace();
            RedRLog.log(RedRLog.REDRCORE, RedRLog.CRITICAL, "Error closing session: " + e.toString());
            ce.ignore();
        }
    }
    
    public void visibilityChanged(boolean b){
    	// TODO do something when visibility changes.
    }
    
    public void clearPrintOutput(){
    	// TODO
    }
    
    public void showLogFile(){
    	// TODO
    }
    
    public void addTab(){
    	// TODO
    }
    
    public void removeCurrentTab(){
    	// TODO
    }
    

        
/*
class RedRQApplication(QApplication):
    def __init__(self, *args):
        QApplication.__init__(self, *args)
        

def main(argv = null):
    if argv == null:
        argv = sys.argv
    //print "starting main application"
    app = RedRQApplication(sys.argv)
    QCoreApplication.setOrganizationName("Red-R")
    QCoreApplication.setOrganizationDomain("red-r.com")
    QCoreApplication.setApplicationName("Red-R")
    //print "setting canvas dlg"
    dlg = OrangeCanvasDlg(app)
    //print "application set"
    qApp.canvasDlg = dlg
    
    //print "showing dlg"
    
    dlg.show()
    
    //# do we need to load a schema, this happens if you open a saved session.
    if Files.exists(sys.argv[-1]) and Files.splitext(sys.argv[-1])[1].lower() == ".rrs": 
        dlg.schema.loadDocument(sys.argv[-1])

    //# for arg in sys.argv[1:]:
    //    # if arg == "-reload":
    //        # dlg.menuItemOpenLastSchema()
    //print "application executed"
    app.exec_()
    
    //# manager.shutdown()
    //# dlg.saveSettings()
    app.closeAllWindows()

def updates():
    #print time.time(), "Starting updates"
    app = redRApplication.RedRQApplication(sys.argv)
    QCoreApplication.setOrganizationName("Red-R");
    QCoreApplication.setOrganizationDomain("red-r.com");
    QCoreApplication.setApplicationName("Red-R");
    updateManager = redRUpdateManager.updateManager(app)
    if RedREnviron.settings["checkForUpdates"]:
        updateManager.checkForUpdate(auto=true)
    print "is avaliable", RedREnviron.settings["updateAvailable"]
    if RedREnviron.settings["updateAvailable"]:
        updateGUI = updateManager.showUpdateDialog()  
        updateGUI = app.exec_()
        app.closeAllWindows()
        RedREnviron.saveSettings()
        return updateGUI
    else:
        return 0
    /*
if __name__ == "__main__":
    # freeze_support()
    wasUpdated = 0
    #if RedREnviron.settings["checkForUpdates"] and not RedREnviron.settings["updateAvailable"]:
    try:
        wasUpdated = updates()
    except:
        redRLog.log(redRLog.REDRCORE, redRLog.CRITICAL,redRLog.formatException())
    print "updated ended with", wasUpdated
    if wasUpdated == 0:
        sys.exit(main())
    else:
        sys.exit()
	*/
        		
	/**
	 * @param args
	 */
//	public static void main(String[] args) {
//    	QApplication.initialize(args);
//
//		
//		try
//		{
//			RedRCanvas canvas = new RedRCanvas();
//		}
//		catch (Exception e)
//		{
//			// we don"t do anything just close
//			System.out.println("Exception found " + e.toString());
//			QApplication.quit();
//		}
//		
//        QApplication.exec();
//        
//	}

}
